# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

from typing import Optional

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        cur1, cur2, cur, ans, carry = l1, l2, None, None, 0
        while cur1 or cur2:
            val1 = cur1.val if cur1 else 0
            val2 = cur2.val if cur2 else 0
            sum = val1 + val2 + carry
            carry = sum // 10
            val = sum % 10
            if not ans:
                ans = cur = ListNode()
            cur.val = val
            cur1 = cur1.next if cur1 else None
            cur2 = cur2.next if cur2 else None
            if cur1 or cur2:
                cur.next = ListNode()
                cur = cur.next
        if carry:
            cur.next = ListNode(carry)
        return ans